define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            function debounce(handle, delay) {
                let time = null;
                return function () {
                    let self = this,
                        arg = arguments;
                    clearTimeout(time);
                    time = setTimeout(function () {
                        handle.apply(self, arg);
                    }, delay)
                }
            }
            var goodsIndex = new Vue({
                el: "#goodsIndex",
                data() {
                    return {
                        //查询条件
                        where: {
                            is_enable: 1,//1=上架,0=下架
                            goods_name: '',//商品名称
                        },
                        goodsData: [],
                        multipleSelection: [],
                        chooseType: 0,
                        activityType: 'all',
                        sort: 'id',
                        order: 'desc',
                        offset: 0,
                        limit: 10,
                        totalPage: 0,
                        currentPage: 1,
                        rowDel: false,
                        allDel: false,
                        upStatus: true,
                        allAjax: true,
                        tableAjax: false,
                        //选择分类
                        categoryOptions: [],
                        popperVisible: false,
                        category_id: "",//选中category_id
                    }
                },
                created() {
                    this.getData();
                },
                methods: {
                    //获取商品分类数据
                    getCategoryOptions() {
                        let that = this;
                        Fast.api.ajax({
                            url: 'health/goods/category/select',
                            loading: false,
                        }, function (ret, res) {
                            console.log(res)
                            that.categoryOptions = res.data;
                            return false;
                        })
                    },
                    // 获取商品列表
                    getData() {
                        let that = this;
                        if (!that.allAjax) {
                            that.tableAjax = true;
                        }
                        let dataAc = {
                            is_enable: that.where.is_enable,
                            goods_name: that.where.goods_name,
                            offset: that.offset,
                            limit: that.limit,
                            sort: that.sort,
                            order: that.order,
                        };
                        Fast.api.ajax({
                            url: 'health/goods/goods/index',
                            loading: false,
                            type: 'GET',
                            data: dataAc
                        }, function (ret, res) {
                            that.goodsData = res.data.rows;
                            that.goodsData.forEach(i => {
                                i.showFlag = false;
                                i.rowDel = false;
                            });
                            that.totalPage = res.data.total;
                            that.allAjax = false;
                            that.tableAjax = false;
                            return false;
                        }, function (ret, res) {
                            that.allAjax = false;
                            that.tableAjax = false;
                        })
                    },
                    goodsOpt(type, id) {
                        let that = this;
                        switch (type) {
                            case 'create':
                                Fast.api.open('health/goods/goods/add', '新增商品', {
                                    callback() {
                                        that.getData();
                                    }
                                })
                                break;
                            case 'edit':
                                Fast.api.open('health/goods/goods/edit/ids/' + id + "?id=" + id + "&type=edit", '编辑商品', {
                                    callback() {
                                        that.getData();
                                    }
                                })
                                break;
                            case 'down':
                                let idArr = []
                                if (that.multipleSelection.length > 0) {
                                    that.multipleSelection.forEach(i => {
                                        idArr.push(i.id)
                                    })
                                    let idss = idArr.join(',')
                                    that.editStatus(idss, 'down')
                                }
                                break;
                            case 'up':
                                let idArrup = []
                                if (that.multipleSelection.length > 0) {
                                    that.multipleSelection.forEach(i => {
                                        idArrup.push(i.id)
                                    })
                                    let idup = idArrup.join(',')
                                    that.editStatus(idup, 'up')
                                }
                                break;
                            case 'del':
                                let ids;
                                if (id) {
                                    ids = id;
                                } else {
                                    let idArr = []
                                    if (that.multipleSelection.length > 0) {
                                        that.multipleSelection.forEach(i => {
                                            idArr.push(i.id)
                                        })
                                        ids = idArr.join(',')
                                    }
                                }
                                if (ids) {
                                    that.$confirm('此操作将删除商品, 是否继续?', '提示', {
                                        confirmButtonText: '确定',
                                        cancelButtonText: '取消',
                                        type: 'warning'
                                    }).then(() => {
                                        Fast.api.ajax({
                                            url: 'health/goods/goods/del/ids/' + ids,
                                            loading: true,
                                            type: 'POST',
                                        }, function (ret, res) {
                                            that.getData();
                                            return false;
                                        })
                                    }).catch(() => {
                                        that.$message({
                                            type: 'info',
                                            message: '已取消删除'
                                        });
                                    });
                                }
                                break;
                            case 'copy':
                                Fast.api.open('health/goods/goods/edit/ids/' + id + "?id=" + id + "&type=copy", '商品详情', {
                                    callback() {
                                        that.getData();
                                    }
                                })
                                break;
                            case 'filter':
                                that.offset = 0;
                                that.limit = 10;
                                that.currentPage = 1;
                                that.getData();
                                break;
                            case 'clear':
                                that.activityType = 'all';
                                that.where.goods_name = '';
                                break;
                            case 'recycle':
                                Fast.api.open('health/goods/goods/recyclebin', '查看回收站')
                                break;
                            default:
                                Fast.api.open('health/goods/goods/edit/ids/' + type.id + "?id=" + type.id + "&type=edit", '编辑商品', {
                                    callback() {
                                        that.getData();
                                    }
                                })
                                break;
                        }
                    },
                    hideup() {
                        for (key in this.selectedRowId) {
                            this.selectedRowId[key] = false;
                        }
                    },
                    sortOrder(sort, order) {
                        this.sort = sort;
                        this.order = order;
                        this.getData();
                    },
                    handleSelectionChange(val) {
                        this.multipleSelection = val;
                    },
                    handleSizeChange(val) {
                        this.offset = 0
                        this.limit = val;
                        this.currentPage = 1;
                        this.getData()
                    },
                    handleCurrentChange(val) {
                        this.currentPage = val;
                        this.offset = (val - 1) * this.limit;
                        this.getData()
                    },
                    editStatus(id, type) {
                        let that = this;
                        Fast.api.ajax({
                            url: `health/goods/goods/setStatus/ids/${id}/status/${type}`,
                            loading: true,
                        }, function (ret, res) {
                            that.getData();
                            return false;
                        })
                    },
                    look(id, type) {
                        let that = this;
                        if (type == 'link') {
                            let clipboard = new Clipboard('.link-copy', {
                                text: () => {
                                    return window.location.host + "/openlink.html?spm=0.2." + id + ".3.1";
                                }
                            })
                            let copynum = 0
                            clipboard.on('success', function () {
                                that.$message({
                                    message: '复制成功',
                                    type: 'success'
                                });
                                copynum++;
                                if (copynum >= 1) {
                                    clipboard.destroy();
                                    clipboard = new Clipboard('.link-copy');
                                };
                            });
                            clipboard.on('error', function () {
                                that.$message.error('复制失败');
                            });
                        } else {
                            Fast.api.ajax({
                                url: `health/goods/goods/look/ids/${id}/type/${type}`,
                                loading: true,
                            }, function (ret, res) {

                                return false;
                            })
                        }
                    },
                    chooseOpt(type) {
                        this.activityType = type
                    },
                    isShoose() {
                        this.chooseType == 0 ? 1 : 0;
                        if (this.chooseType == 0) {
                            this.activityType = 'all';
                            this.priceFrist = "";
                            this.priceLast = "";
                        }
                    },
                    tableRowClassName({
                        rowIndex
                    }) {
                        if (rowIndex % 2 == 1) {
                            return 'bg-color';
                        }
                        return '';
                    },
                    tableCellClassName({
                        columnIndex
                    }) {
                        if (columnIndex == 2) {
                            return 'cell-left';
                        }
                        return '';
                    },
                    debounceFilter: debounce(function () {
                        this.getData()
                    }, 1000),
                },
                watch: {
                    'where.is_enable'(newVal, oldVal) {
                        if (newVal != oldVal) {
                            this.offset = 0;
                            this.limit = 10;
                            this.currentPage = 1;
                            this.getData();
                        }
                    },
                    searchKey(newVal, oldVal) {
                        if (newVal != oldVal) {
                            this.offset = 0;
                            this.limit = 10;
                            this.currentPage = 1;
                            this.debounceFilter();
                        }
                    },
                },
            })
        },
        add: function () {
            var i = 1;
            //之前的添加规格值
            $('#space').on('click', '.btn-primary', function (e) {
                var value = $(this).parent().prev().children()[0].value;
                // var value = $(this).parent().prev().prev().prev().children()[0].value;
                // console.log($(this).parent().prev().prev().prev());
                if (value == '') {
                    layer.msg('规格值不能为做空');
                    return false;
                }
                var space_list = `<div class="spaceItem">
									<div class="form-group skuMain">
											<label class="control-label col-xs-12 col-sm-2">规格:</label>
											<div class="col-xs-6 col-sm-6"><input type="text" data-rule="required" name="attr[]" maxlength="22" placeholder="请输入规格名称"  class="form-control"></div>
										<div class="col-xs-4 col-sm-2" style="text-align: right;"><span class="btn btn-danger move" >移除</span> </div>
										<div class="col-xs-8 col-sm-8 col-xs-offset-2 col-sm-offset-2 skuChildrenBox"></div>
									</div>
									<div class="form-group skuMain">
										<label class="control-label col-xs-12 col-sm-2">售价:</label>
										<div class="col-xs-6 col-sm-6"><input type="number" data-rule="required" name="price[]"  placeholder="请输入售价"  class="form-control"></div>
									</div>
                                    <div class="form-group skuMain">
                                        <label class="control-label col-xs-12 col-sm-2">库存:</label>
                                        <div class="col-xs-6 col-sm-6">
                                            <input type="number" data-rule="required" name="stock[]" placeholder="请输入库存"
                                                class="form-control">
                                        </div>
                                    </div>
									<div class="form-group skuMain">
											<label for="c-attr${i}" class="control-label col-xs-12 col-sm-2">规格图片:</label>
											<div class="col-xs-12 col-sm-8">
												<div class="input-group">
													<input id="c-attr${i}" data-rule="required" class="form-control" size="50" name="images[]" type="text">
													<div class="input-group-addon no-border no-padding">
														<span><button type="button" id="plupload-attr${i}" class="btn btn-danger plupload" data-input-id="c-attr${i}" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="false" data-preview-id="p-attr${i}"><i class="fa fa-upload"></i> 上传</button></span>
														<span><button type="button" id="fachoose-attr${i}" class="btn btn-primary fachoose" data-input-id="c-attr${i}" data-mimetype="image/*" data-multiple="false"><i class="fa fa-list"></i> 选择</button></span>
													</div>
													<span class="msg-box n-right" for="c-attr${i}"></span>
												</div>
												<ul class="row list-inline plupload-preview" id="p-attr${i}"></ul>
											</div>
									</div>
								</div>`;
                $('#space').append(space_list);
                i++;
                require(['upload'], function (Upload) {
                    Upload.api.plupload($(".plupload"), function () {
                        $(".btn-refresh").trigger("click");
                    });
                });
            });
            //移除规格值
            //移除规格
            $('#space').on('click', '.btn-danger', function (e) {
                //判断是否是最后一个规格了
                // if($('.skuMain').length == 1){
                // 	layer.msg('规格值不能为做空');
                // 	return false;
                // }else{
                $(this).parent().parent().remove();
                // }

            });

            Controller.api.bindevent();
        },
        edit: function () {
            //添加规格值
            var i = 0;
            $('#space').on('click', '.btn-primary', function (e) {
                if (i > 0) {
                    i++
                } else {
                    i = $(this).attr('data');
                    i++
                }


                var value = $(this).parent().prev().children()[0].value;
                if (value == '') {
                    layer.msg('规格值不能为做空');
                    return false;
                }
                var space_list = `<div class="spaceItem">
            						<div class="form-group skuMain">
            								<label class="control-label col-xs-12 col-sm-2">规格:</label>
            								<div class="col-xs-6 col-sm-6"><input type="text" data-rule="required" name="attr[]" maxlength="22" placeholder="请输入规格名称"  class="form-control"></div>
            							<div class="col-xs-4 col-sm-2" style="text-align: right;"><span class="btn btn-danger move" >移除</span> </div>
            							<div class="col-xs-8 col-sm-8 col-xs-offset-2 col-sm-offset-2 skuChildrenBox"></div>
            						</div>
            						<div class="form-group skuMain">
            							<label class="control-label col-xs-12 col-sm-2">售价:</label>
            							<div class="col-xs-6 col-sm-6"><input type="number" data-rule="required" name="price[]" maxlength="22" placeholder="请输入售价"  class="form-control"></div>
            						</div>
                                    <div class="form-group skuMain">
                                        <label class="control-label col-xs-12 col-sm-2">库存:</label>
                                        <div class="col-xs-6 col-sm-6">
                                            <input type="number" data-rule="required" name="stock[]" placeholder="请输入库存"
                                                class="form-control">
                                        </div>
                                    </div>
            						<div class="form-group skuMain">
            								<label for="c-attr${i}" class="control-label col-xs-12 col-sm-2">规格图片:</label>
            								<div class="col-xs-12 col-sm-8">
            									<div class="input-group">
            										<input id="c-attr${i}" data-rule="required" class="form-control" size="50" name="images[]" type="text">
            										<div class="input-group-addon no-border no-padding">
            											<span><button type="button" id="plupload-attr${i}" class="btn btn-danger plupload" data-input-id="c-attr${i}" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="false" data-preview-id="p-attr${i}"><i class="fa fa-upload"></i> 上传</button></span>
            											<span><button type="button" id="fachoose-attr${i}" class="btn btn-primary fachoose" data-input-id="c-attr${i}" data-mimetype="image/*" data-multiple="false"><i class="fa fa-list"></i> 选择</button></span>
            										</div>
            										<span class="msg-box n-right" for="c-attr${i}"></span>
            									</div>
            									<ul class="row list-inline plupload-preview" id="p-attr${i}"></ul>
            								</div>
            						</div>
            					</div>`;
                $('#space').append(space_list);
                require(['upload'], function (Upload) {
                    Upload.api.plupload($(".plupload"), function () {
                        $(".btn-refresh").trigger("click");
                    });
                });
            });
            //移除规格值
            //移除规格
            $('#space').on('click', '.move', function (e) {
                //判断是否是最后一个规格了
                // if($('.skuMain').length == 1){
                // 	layer.msg('规格值不能为做空');
                // 	return false;
                // }else{
                $(this).parent().parent().parent().remove();
                // }

            });
            Controller.api.bindevent();
        },
        select: function () {
            function debounce(handle, delay) {
                let time = null;
                return function () {
                    let self = this,
                        arg = arguments;
                    clearTimeout(time);
                    time = setTimeout(function () {
                        handle.apply(self, arg);
                    }, delay)
                }
            }
            var goodsSelect = new Vue({
                el: "#goodsSelect",
                data() {
                    return {
                        categoryData: [],
                        searchWhere: '',
                        goodsList: [],
                        totalPage: 0,
                        offset: 0,
                        currentPage: 1,
                        multiple: new URLSearchParams(location.search).get('multiple'),
                        category_id: null,
                        selectedIds: []
                    }
                },
                mounted() {
                    if (new URLSearchParams(location.search).get('ids')) {
                        this.selectedIds = new URLSearchParams(location.search).get('ids').split(',')
                    }
                    this.getList();
                    this.categoryData = Config.category
                },
                methods: {
                    getList(id) {
                        let that = this;
                        let url = "health/goods/goods/select";
                        if (id) {
                            url = 'health/goods/goods/select?category_id=' + id
                        }
                        Fast.api.ajax({
                            url: url,
                            data: {
                                limit: 10,
                                offset: that.offset,
                                search: that.searchWhere
                            },
                            type: 'GET'
                        }, function (ret, res) {
                            that.goodsList = res.data.rows;
                            that.goodsList.forEach(g => {
                                that.$set(g, 'checked', false)
                            })
                            let selectData = []
                            that.goodsList.forEach(g => {
                                if (that.selectedIds.includes(g.id + '')) {
                                    selectData.push(g)
                                }
                            })
                            that.$nextTick(() => {
                                selectData.forEach(row => {
                                    that.$refs.multipleTable.toggleRowSelection(row);
                                });
                            })
                            that.totalPage = res.data.total;
                            return false;
                        })
                    },
                    singleSelectionChange(row) {
                        this.selectedIds = []
                        this.selectedIds.push(row.id)
                        this.goodsList.forEach(g => {
                            if (g.id == row.id) {
                                this.$set(g, 'checked', true)
                            } else {
                                this.$set(g, 'checked', false)
                            }
                        })
                        this.$forceUpdate()
                    },
                    multipleSelectionChange(val) {
                        val.forEach(g => {
                            if (!this.selectedIds.includes(g.id + '')) {
                                this.selectedIds.push(g.id + '')
                            }
                        })
                    },
                    SelectionChange(selection, row) {
                        if (this.selectedIds.indexOf(row.id + '') != -1) {
                            this.selectedIds.splice(this.selectedIds.indexOf(row.id + ''), 1)
                        }
                    },
                    changeClick(val) {
                        this.currentPage = val;
                        this.offset = 10 * (val - 1);
                        if (this.category_id == null) {
                            this.getList()
                        } else {
                            this.getList(this.category_id)
                        }
                    },
                    operation() {
                        let that = this;
                        let domain = window.location.origin;
                        if (this.selectedIds.length == 0) {
                            return false
                        }
                        let ids = this.multiple == 'true' ? this.selectedIds : this.selectedIds[this.selectedIds.length - 1]
                        Fast.api.ajax({
                            url: 'health/goods/goods/index?goods_ids=' + ids + "&per_page=999999999&type=all",
                            loading: false,
                        }, function (ret, res) {
                            Fast.api.close({
                                data: that.multiple == 'true' ? res.data.rows : res.data.rows[0],
                            });
                            return false;
                        }, function () {
                            return false;
                        })
                    },
                    debounceFilter: debounce(function () {
                        this.getList()
                    }, 1000),
                    showLeft(p, c, a, s) {
                        if (p != null && a === null && c === null && s === null) {
                            this.categoryData[p].show = !this.categoryData[p].show;
                        }
                        if (p != null && c != null && a == null && s === null) {
                            this.categoryData[p].children[c].show = !this.categoryData[p].children[c].show;
                        }
                        if (p != null && c != null && a != null && s === null) {
                            this.categoryData[p].children[c].children[a].show = !this.categoryData[p].children[c].children[a].show;
                        }
                        this.$forceUpdate();
                    },
                    selectCategoryLeft(p, c, a, s) {
                        this.categoryData.forEach(i => {
                            i.selected = false;
                            if (i.children && i.children.length > 0) {
                                i.children.forEach(j => {
                                    j.selected = false;
                                    if (j.children && j.children.length > 0) {
                                        j.children.forEach(k => {
                                            k.selected = false;
                                            if (k.children && k.children.length > 0) {
                                                k.children.forEach(l => {
                                                    l.selected = false;
                                                })
                                            }
                                        })
                                    }
                                })
                            }
                        })
                        let category_id = null;
                        if (p != null && a === null && c === null && s === null) {
                            this.categoryData[p].selected = !this.categoryData[p].selected;
                            category_id = this.categoryData[p].id
                        }
                        if (p != null && c != null && a == null && s === null) {
                            this.categoryData[p].children[c].selected = !this.categoryData[p].children[c].selected;
                            category_id = this.categoryData[p].children[c].id
                        }
                        if (p != null && c != null && a != null && s === null) {
                            this.categoryData[p].children[c].children[a].selected = !this.categoryData[p].children[c].children[a].selected;
                            category_id = this.categoryData[p].children[c].children[a].id
                        }
                        if (p != null && c != null && a != null && s != null) {
                            this.categoryData[p].children[c].children[a].children[s].selected = !this.categoryData[p].children[c].children[a].children[s].selected;
                            category_id = this.categoryData[p].children[c].children[a].children[s].id
                        }
                        this.category_id = category_id;
                        this.offset = 0;
                        this.getList(category_id)
                        this.$forceUpdate();
                    },
                },
                watch: {
                    searchWhere(newVal, oldVal) {
                        if (newVal != oldVal) {
                            this.offset = 0;
                            this.currentPage = 1;
                            this.categoryData.forEach(i => {
                                i.selected = false;
                                if (i.children && i.children.length > 0) {
                                    i.children.forEach(j => {
                                        j.selected = false;
                                        if (j.children && j.children.length > 0) {
                                            j.children.forEach(k => {
                                                k.selected = false;
                                                if (k.children && k.children.length > 0) {
                                                    k.children.forEach(l => {
                                                        l.selected = false;
                                                    })
                                                }
                                            })
                                        }
                                    })
                                }
                            })
                            this.debounceFilter();
                        }
                    },
                },
            })
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});